from datetime import datetime
from PyQt6.QtCore import QObject, pyqtSignal, Qt, QThread
from PyQt6.QtGui import QTextCursor, QTextCharFormat, QColor, QFont
from PyQt6.QtWidgets import QPlainTextEdit


class LogSignal(QObject):
    """用于跨线程通信的信号容器"""
    log_received = pyqtSignal(str, str, str)  # level, message, time


class LogManager(QObject):
    def __init__(self):
        super().__init__()
        self._text_edit = None
        self.signals = LogSignal()
        self.signals.log_received.connect(self._append_log)
        self._init_formats()
        self.time_format = "%Y-%m-%d %H:%M:%S"

    def bind_widget(self, text_edit):
        """绑定日志显示控件"""
        self._text_edit = text_edit
        self._text_edit.setReadOnly(True)
        self._text_edit.setFont(QFont("Consolas", 10))
        self._text_edit.setLineWrapMode(QPlainTextEdit.LineWrapMode.NoWrap)
        self._text_edit.setMaximumBlockCount(5000)

    def _init_formats(self):
        """初始化日志格式"""
        self.formats = {
            "DEBUG": self._create_format("#666666"),
            "INFO": self._create_format("#009900"),
            "WARNING": self._create_format("#FF9900", bold=True),
            "ERROR": self._create_format("#FF0000", bold=True, underline=True),
            "CRITICAL": self._create_format("#FFFFFF", bg_color="#FF0000")
        }

    def _create_format(self, color, bold=False, underline=False, bg_color=None):
        """创建文本格式模板"""
        fmt = QTextCharFormat()
        fmt.setForeground(QColor(color))
        if bold: fmt.setFontWeight(QFont.Weight.Bold)
        if underline: fmt.setUnderlineStyle(QTextCharFormat.UnderlineStyle.SingleUnderline)
        if bg_color: fmt.setBackground(QColor(bg_color))
        return fmt

    def log(self, level: str, message: str):
        """线程安全记录日志"""
        timestamp = datetime.now().strftime(self.time_format)
        if QThread.currentThread() == self.thread():
            self._append_log(level, message, timestamp)
        else:
            self.signals.log_received.emit(level, message, timestamp)

    def _append_log(self, level: str, message: str, timestamp: str):
        """实际写入日志"""
        if not self._text_edit:
            return

        cursor = self._text_edit.textCursor()
        cursor.movePosition(QTextCursor.MoveOperation.End)

        # 插入时间戳
        time_fmt = self._create_format("#666666")
        cursor.insertText(f"[{timestamp}] ", time_fmt)

        # 插入级别标签
        level_fmt = self.formats.get(level.upper(), self.formats["INFO"])
        cursor.insertText(f"[{level.upper()}] ", level_fmt)

        # 插入消息正文
        cursor.insertText(f"{message}\n", self.formats["INFO"])

        # 自动滚动
        self._text_edit.ensureCursorVisible()